<template>
  <MyDrawer ref="myRef" title="经纪人" @submit="submit" width="55%" :disabled="false">
    <el-form :model="drawerProps.row" label-width="120" :rules="rules" ref="formRef">
      <div class="w-1/2">
        <el-form-item prop="username" label="用户名称">
          <el-input v-model="drawerProps.row.username"></el-input>
        </el-form-item>
        <!-- <el-form-item prop="password" label="密码">
          <el-input v-model="drawerProps.row.password" type="password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword" label="再次确认">
          <el-input v-model="drawerProps.row.rePassword" type="password"></el-input>
        </el-form-item> -->
        <el-form-item prop="avatar" label="头像选择">
          <ChooseFile v-model:url="drawerProps.row.avatar"></ChooseFile>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="drawerProps.row.phone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="drawerProps.row.realName"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="drawerProps.row.idCard"></el-input>
        </el-form-item>
        <el-form-item label="二维码">
          <div>
            <div class="w-[150px] h-[150px]" style="border: 2px dashed var(--el-color-info-light-3)">
              <el-image :src="drawerProps.row.qrcode"></el-image>
            </div>
            <!-- <el-button class="mt-10px">生成二维码</el-button> -->
          </div>
        </el-form-item>
      </div>
      <el-form-item label="驻守楼盘">
        <div>
          <el-button @click="openLou">添加驻守楼盘</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-tag
          v-for="(p, index) in drawerProps.row.louPan"
          :key="index"
          type="info"
          effect="light"
          class="mr-10px mt-10px"
          closable
          @close="changeList(p.id)"
          >{{ p.name }}</el-tag
        >
      </el-form-item>
    </el-form>
    <chooseLou ref="louRef" @get-bind-lous="getLous" left-title="楼盘列表" right-title="驻守楼盘"></chooseLou>
  </MyDrawer>
</template>

<script setup lang="ts">
import MyDrawer from "@/components/MyDrawer/index.vue";
import { onBeforeMount, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { validUsername, checkPhoneNumber, checkIdCard } from "@/utils/eleValidate";
// import md5 from "js-md5";
import chooseLou from "./chooseLou.vue";
import { getLous as getLousList } from "@/api/modules/broker";
import { genCode } from "@/api/modules/account";
import ChooseFile from "@/components/ChooseFile/index.vue";

const list = ref([]);

const getLousApi = async (name: string = "") => {
  const { data } = await getLousList({ name });
  list.value = data as any;
};

const louRef = ref<InstanceType<typeof chooseLou> | null>();

const openLou = () => {
  let hasChooseLous: any = [];
  if (drawerProps.value.row.louPan) {
    hasChooseLous = drawerProps.value.row.louPan.map((e: any) => e.id);
  }

  const inAllList = list.value.filter((e: any) => !hasChooseLous.includes(e.id));
  louRef.value?.acceptParams({
    inNowList: drawerProps.value.row.louPan ? drawerProps.value.row.louPan : [],
    allList: list.value,
    inAllList
  });
};

const myRef = ref<InstanceType<typeof MyDrawer> | null>();

interface DrawerProps {
  row: any;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}

const initData: any = {
  username: "",
  password: "",
  rePassword: "",
  avatar: "",
  phone: "",
  realName: "",
  idCard: "",
  status: false
};

const getLous = (val: any) => {
  drawerProps.value.row.louPan = val;
};

const changeList = (id: number) => {
  const index = drawerProps.value.row.louPan.findIndex((e: any) => e.id === id);
  if (index !== -1) {
    drawerProps.value.row.louPan.splice(index, 1);
  }
};

// 密码确认校验;
// const validRePassword = (rule: any, value: any, callback: any) => {
//   if (drawerProps.value.row.password === "") {
//     return callback();
//   }

//   if (value !== drawerProps.value.row.password) {
//     return callback(new Error("两次密码不一致"));
//   } else {
//     callback();
//   }
// };

const rules: FormRules = {
  username: [
    { required: true, message: "名称必须", trigger: "blur" },
    { validator: validUsername, trigger: "blur" },
    { min: 5, max: 20, message: "账号名称长度在5-20之间", trigger: "blur" }
  ],
  // password: [
  //   { min: 8, max: 16, message: "字符在8-16之间", trigger: "blur" },
  //   { validator: validPassword, trigger: "blur" }
  // ],
  avatar: [{ required: true, message: "头像不可为空", trigger: "blur" }],
  // rePassword: [{ validator: validRePassword, trigger: "blur" }],
  phone: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  realName: [
    { required: true, message: "姓名不可空", trigger: "blur" },
    { max: 20, min: 2, message: "字数2-20个", trigger: "blur" }
  ],
  idCard: [{ validator: checkIdCard, required: true, trigger: "blur" }]
};

const drawerProps = ref<DrawerProps>({
  row: JSON.parse(JSON.stringify(initData))
});

const acceptParams = (params: any) => {
  drawerProps.value = params;
  // drawerProps.value.row.password = "";
  myRef.value?.acceptParams();
};

const formRef = ref<FormInstance>();

const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        // if (drawerProps.value.row.password !== "") {
        //   drawerProps.value.row.password = md5(drawerProps.value.row.password);
        //   drawerProps.value.row.rePassword = md5(drawerProps.value.row.rePassword);
        // } else {
        //   drawerProps.value.row.password = "";
        // }

        await drawerProps.value.api!(drawerProps.value.row);
        ElMessage.success("成功!");
        await drawerProps.value.getTable!();
        myRef.value?.close();
      } catch (error) {}
    }
  });
};

onBeforeMount(() => {
  Promise.all([getLousApi()]);
});

// 监听二维码
watch(
  () => drawerProps.value.row.id,
  async () => {
    if (drawerProps.value.row.qrcode === "") {
      console.log("无二维码");
      const { data } = await genCode({ id: drawerProps.value.row.id });
      drawerProps.value.row.qrcode = data;
      await drawerProps.value.getTable!();
    }
  },
  {}
);

defineExpose({ acceptParams });
</script>

<style></style>
